import socket
from app.log_config import monitor_logger
from datetime import datetime


heartbeatMap = {
    "zmj_heart_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}


def start_udp_server(server_ip, server_port):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_socket.bind((server_ip, server_port))
    monitor_logger.info(f"UDP server listening on {server_ip}:{server_port}")

    try:
        while True:
            data, addr = server_socket.recvfrom(1024)
            message = data.decode()
            monitor_logger.info(f"Received message: {message} from {addr}")

            if message.find('heartbeat_') != -1:
                heart_client_name = message.split('_')[1]
                monitor_logger.info(f"Received heartbeat message... {heart_client_name}")
                timeStamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                heartbeatMap[f"{heart_client_name}_heart_time"] = timeStamp

            else:
                monitor_logger.info("Invalid command.")
    except KeyboardInterrupt:
        monitor_logger.info("UDP server is shutting down.")
    finally:
        monitor_logger.info("Closing UDP server.")
        server_socket.close()

# if __name__ == "__main__":
#     UDP_SERVER_IP = "127.0.0.1"
#     UDP_SERVER_PORT = 12345
#     start_udp_server(UDP_SERVER_IP, UDP_SERVER_PORT)